package webApiEntities.Responses;

import java.lang.reflect.Type;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class ResponseClassAdapter implements JsonSerializer<BasicResponseMessage>, JsonDeserializer<BasicResponseMessage> {

	@Override
	  public JsonElement serialize(BasicResponseMessage src, Type typeOfSrc, JsonSerializationContext context) {
	      JsonObject result = new JsonObject();
	      result.add("type", new JsonPrimitive(src.getClass().getSimpleName()));
	      GsonBuilder builder = new GsonBuilder();
	      result.add("properties", builder.create().toJsonTree(src, typeOfSrc));
	      return result;
	  }


	  @Override
	  public BasicResponseMessage deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
	        throws JsonParseException {
	    JsonObject jsonObject = json.getAsJsonObject();
	    String type = jsonObject.get("type").getAsString();
	    JsonElement element = jsonObject.get("properties");

	    try {            
	        String thepackage = "webApiEntities.Responses.";
	        GsonBuilder builder = new GsonBuilder();
	        return (BasicResponseMessage) builder.create().fromJson(element, Class.forName(thepackage + type));
	    } catch (ClassNotFoundException cnfe) {
	        throw new JsonParseException("Unknown element type: " + type, cnfe);
	    }
	  }
	
}
